package org.luxor.commons.security.component;

import org.luxor.commons.core.utils.HttpContextUtils;
import org.luxor.commons.core.utils.StrKit;
import org.luxor.commons.core.web.RestStatus;
import org.luxor.commons.core.web.data.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;
import org.springframework.util.MimeTypeUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 403 禁止访问, 鉴权失败处理器
 * @author yanxinming @date 2020/06/03
 */
public class RestAccessDeniedHandler extends AccessDeniedHandlerImpl {
    private static final Logger log = LoggerFactory.getLogger(RestAccessDeniedHandler.class);

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        response.setStatus(HttpStatus.OK.value());
        response.setCharacterEncoding(StrKit.CHARSET_NAME);
        response.setContentType(MimeTypeUtils.APPLICATION_JSON_VALUE);

        log.debug("当前来源IP:[{}] 禁止访问:[{}]", HttpContextUtils.getRemoteAddr(request), request.getRequestURI());

        R result = new R<>(RestStatus.FORBIDDEN, e.getMessage());
        HttpContextUtils.sendJson(response, result);
    }
}
